import UserModel from '../model/UserModel.js'

import CryptoJS from "crypto-js";

class UserService {
  async loginByUserName (username, password, phone) {

    //插入数据
    //await 跟随promise
    const userModel = await UserModel.create({
      username,
      password: CryptoJS.MD5(password).toString(),
      phone
    })

    //res 就是一个userModel对象

    return {
      code: 200,
      result: userModel,
      token: '1234'
    }
  }

  async registerByUserName (username, password, phone) {

    //await 跟随promise
    const userModel = await UserModel.create({
      username,
      password,
      phone
    })

    //res 就是一个userModel对象

    return {
      code: 200,
      result: userModel,
      msg: 'success',
      token: '1234'
    }
  }

  async findUser ({ id, username }) {
    const where = {}

    id && Object.assign(where, { id });
    username && Object.assign(where, { username });

    return await UserModel.findOne({
      attributes: ['id', 'username', 'password', 'phone', 'createdAt'],
      where: where
    })
  }

  async deleteUser (id) {
    const user = await UserModel.findOne({
      where: {
        id
      }
    })

    if (user) {
      user.destroy()
    }
  }
}

let instance = new UserService()

export default instance;